package com.abe.libcore.utils

import android.os.Environment
import java.io.File
import java.io.IOException

object FileUtils {
    /**
     * 存在删除后重新创建
     * @param path 文件夹路径
     * @param fileName 文件名
     */
    fun createNewFile(path: String, fileName: String): File {
        val fullFileName = path + File.separator + fileName
        return createNewFile(fullFileName)
    }

    /**
     * 存在删除后重新创建
     * @param fullFileName
     */
    fun createNewFile(fullFileName: String): File {
        deleteFile(fullFileName)
        return createFile(fullFileName)
    }

    /**
     * 存在则返回，不创建
     * @param path 文件夹路径
     * @param fileName 文件名
     */
    fun createFile(path: String, fileName: String): File {
        val fullFileName = path + File.separator + fileName
        return createFile(fullFileName)
    }

    /**
     * 存在则返回，不创建
     *@param fullFileName
     */
    fun createFile(fullFileName: String): File {
        val file = File(fullFileName)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return file
    }

    /**
     *存在即删除
     * @param path 文件夹路径
     * @param fileName 文件名
     */
    fun deleteFile(path: String, fileName: String): Boolean {
        val fullFileName = path + File.separator + fileName
        return deleteFile(fullFileName)
    }

    /**
     *存在即删除
     *@param fullFileName
     */
    fun deleteFile(fullFileName: String): Boolean {
        if (fileIsExists(fullFileName)) {
            val f = File(fullFileName)
            return f.delete()
        }
        return true
    }

    /**
     * 判断文件是否存在
     * @param path 文件夹路径
     * @param fileName 文件名
     */
    fun fileIsExists(path: String, fileName: String): Boolean {
        val fullFileName = path + File.separator + fileName
        return fileIsExists(fullFileName)
    }

    /**
     * 判断文件是否存在
     *@param fullFileName 文件路径
     */
    fun fileIsExists(fullFileName: String): Boolean {
        try {
            val f = File(fullFileName)
            if (!f.exists()) {
                return false
            }
        } catch (e: Exception) {
            return false
        }
        return true
    }

    /**
     * 检查文件夹，不存在即创建
     *@param path 文件夹路径
     */
    fun createDir(path: String) {
        //文件夹检查，不存在则创建
        if (Environment.getExternalStorageState() == (Environment.MEDIA_MOUNTED)) {
            //文件夹
            val dir = File(path)
            if (!dir.exists()) {
                dir.mkdirs()
            }
        }
    }
}